import uuid

from rest_framework.views import APIView
from rest_framework.response import Response
from ext.per import UserPermission, ManagerPermission, BossPermission
from api import models
from ext import code
from ext.view import NbApiView
from ext.throttle import IPThrottle,UserThrottle


class LoginView(APIView):
    authentication_classes = []
    permission_classes = []
    throttle_classes = [IPThrottle, ]

    def post(self, request):
        # 接受用户提交的用户名和密码
        user = request.data.get("username")
        pwd = request.data.get("password")

        # 数据库校验
        user_object = models.UserInfo.objects.filter(username=user, password=pwd).first()
        if not user_object:
            return Response({"code": code.ERROR_CODE, "msg": "用户名或密码错误"})

        # 正确
        token = str(uuid.uuid4())
        user_object.token = token
        user_object.save()

        return Response("返回成功")


class UserView(NbApiView):
    permission_classes = [BossPermission, ManagerPermission, UserPermission,]

    def get(self, request):
        print(request.user, request.auth)
        return Response("返回成功")


class OrderView(NbApiView):
    permission_classes = [BossPermission, ManagerPermission, ]

    def get(self, request):
        self.dispatch()
        print(request.user, request.auth)
        return Response("返回成功")


class AvatarView(NbApiView):
    permission_classes = [BossPermission, UserPermission]
    throttle_classes = [UserThrottle, ]

    def get(self, request):
        return Response("返回成功")
